package com.hq.fxh.imageLoader.video;

import android.os.Bundle;

import com.hq.fxh.No1_Infromation.Video.Activity.VideoOpenSelectActivity;
import com.hq.fxh.No1_Infromation.Video.Adapter.VideoGridAdapter;
import com.hq.fxh.R;
import com.hq.fxh.Utils.LogUtils;
import com.hq.fxh.Utils.StatesBarUtils;
import com.hq.fxh.imageLoader.ImageBaseActivity;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;


import java.io.Serializable;
import java.util.List;

import cn.jiguang.analytics.android.api.JAnalyticsInterface;

/**
 * 视频的加载界面   注意 视频选择不需要剪裁
 */
public class SelectVideoActivity extends ImageBaseActivity implements VideoDataSource.OnVideosLoadedListener, VideoGridAdapter.OnVideoItemClickListener, VideoPicker.OnVideoSelectedListener, View.OnClickListener {

    public static final int REQUEST_PERMISSION_STORAGE = 0x01;
    public static final int REQUEST_PERMISSION_CAMERA = 0x02;

    private VideoPicker videoPicker;

    private GridView mGridView;  //视频展示控件
    private TextView mBtnDir;      //文件夹切换按钮
    private List<VideoFolder> mVideoFolders;   //所有的视频文件夹
    private VideoGridAdapter mVideoGridAdapter;  //视频九宫格展示的适配器
    private VideoFolder OneVideoFolder;
    private boolean isTransFolder;
    private int REQUEST_CODE=1234;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_selectvideo;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatesBarUtils.setWindowColor(this, R.color.red);
        videoPicker = VideoPicker.getInstance();
        Intent intent = this.getIntent();
        OneVideoFolder = (VideoFolder) intent.getSerializableExtra("OneVideoFolder");
        isTransFolder = intent.getBooleanExtra("isTransFolder", false);
        //视频加载完成是回调该接口
        videoPicker.addOnVideoSelectedListener(this);
        videoPicker.setMultiMode(false);
        findViewById(R.id.btn_back).setOnClickListener(this);
        mBtnDir = (TextView) findViewById(R.id.btn_dir);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("视频");
        mBtnDir.setOnClickListener(this);
        mGridView = (GridView) findViewById(R.id.gridview);
        mVideoGridAdapter = new VideoGridAdapter(this, null);

        if (null != OneVideoFolder && isTransFolder) {
            mVideoGridAdapter.refreshData(OneVideoFolder.videos);
            tv_title.setText(OneVideoFolder.name);
            mBtnDir.setVisibility(View.GONE);
            mVideoGridAdapter.setShowCamera(false);
        } else {
            mVideoGridAdapter.setShowCamera(true);
        }
//        onVideoSelected(0, null, false);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //加载手机中的视频数据
                new VideoDataSource(this, null, this);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_STORAGE);
            }
        }
    }

    /**
     * 6.0以上权限检查
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                new VideoDataSource(this, null, this);
            } else {
                showToast("权限被禁止，无法选择本地视频");
            }
        } else if (requestCode == REQUEST_PERMISSION_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //录像
                videoPicker.takeRecord(this, VideoPicker.REQUEST_VIDEO_TAKE);
            } else {
                showToast("权限被禁止，无法打开相机");
            }
        }

    }



    @Override
    protected void onResume() {
        super.onResume();
        JAnalyticsInterface.onPageStart(this, "选择视频相册");
    }

    @Override
    protected void onPause() {
        super.onPause();
        JAnalyticsInterface.onPageEnd(this, "选择视频相册");
    }

    @Override
    protected void onDestroy() {
        videoPicker.removeOnVideoSelectedListener(this);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_dir) {
            //点击全部视频
            if (mVideoFolders == null) {
                Toast.makeText(SelectVideoActivity.this, "您的手机没有视频", Toast.LENGTH_SHORT).show();
                return;
            }
            //点击文件夹按钮
            Bundle bundle = new Bundle();
            bundle.putSerializable("VideoFolders", (Serializable) mVideoFolders);
            //      IntentUtils.openActivity(SelectVideoActivity.this,  .class, bundle);
        } else if (id == R.id.btn_back) {
            //点击返回按钮
            finish();
        }
    }


    /**
     * 点击grid每一项的事件回调
     *
     * @param view
     * @param videoItem
     * @param position
     */
    @Override
    public void onVideoItemClick(View view, VideoItem videoItem, int position) {
        LogUtils.e(position+"视频选择");

        //根据是否有相机按钮确定位置
//        position = videoPicker.isShowCamera() ? position - 1 : position;
        //单选视频 直接返回选中的视频
       videoPicker.clearSelectedVideos();
        videoPicker.addSelectedVideoItem(position, mVideoGridAdapter.getItem(position), true);
        startActivity(new Intent(SelectVideoActivity.this,VideoOpenSelectActivity.class));

        //单选视频 直接返回选中的视频
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null) {
            //如果从预览界面返回  判断是否在预览界面选择了原图
            if (resultCode == VideoPicker.RESULT_VIDEO_BACK) {
                //从预览界面接收是否选择原图

            } else {
                //从拍照界面返回
                //点击 X , 没有选择照片
                if (data.getSerializableExtra(VideoPicker.EXTRA_VIDEO_ITEMS) == null) {
                    //什么都不做
                } else {
                    //说明是从裁剪页面过来的数据，直接返回就可以  应该是从录像界面返回的视频数据  还未作处理
                    setResult(VideoPicker.RESULT_VIDEO_ITEMS, data);
                    finish();
                }
            }
        }
        //录像的结果返回事件
        if (resultCode == RESULT_OK && requestCode == VideoPicker.REQUEST_VIDEO_TAKE) {
            //发送广播通知视频增加了
            VideoPicker.galleryAddPic(this, videoPicker.getTakeVideoFile());
            VideoItem videoItem = new VideoItem();
            videoItem.path = videoPicker.getTakeVideoFile().getAbsolutePath();
            videoPicker.clearSelectedVideos();
            //添加选中这个录像视频
            videoPicker.addSelectedVideoItem(0, videoItem, true);
            //更新界面设置录像的这个视频为选中状态  在Adapter中使用接口实现
//            Intent intent = new Intent();
//            intent.putExtra(VideoPicker.EXTRA_RESULT_VIDEO_ITEMS, videoPicker.getSelectedVideos());
//            setResult(VideoPicker.RESULT_VIDEO_ITEMS, intent);   //单选不需要裁剪，返回数据
//            finish();
        }
    }

    @Override
    public void onVideosLoaded(List<VideoFolder> videoFolders) {
        this.mVideoFolders = videoFolders;
        videoPicker.setVideoFolders(videoFolders);
        if (videoFolders.size() == 0) mVideoGridAdapter.refreshData(null);
        else if (!isTransFolder) {
            mVideoGridAdapter.refreshData(videoFolders.get(0).videos);
        }
        //视频点击的监听事件
        mVideoGridAdapter.setOnVideoItemClickListener(this);
        mGridView.setAdapter(mVideoGridAdapter);
    }

    @Override
    public void onVideoSelected(int position, VideoItem item, boolean isAdd) {

    }
}
